<?php

namespace Module\Admin;

use Manager\Options as Manager;
use W3\Html;

!defined('W3_ROOT_DIR') AND exit;

/**
 * 评论设置组件
 *
 * @author edikud
 * @date 2022/10/22
 * @copyright Copyright (c) 2022 W3 (http://www.mcooo.com)
 * @license GNU General Public License 2.0
 */
class Discussion extends Manager
{
    /**
     * 初始化
     *
     * @access protected
     * @return void
     */
    protected function init()
    {
		# 定义变量默认数据
        $this->parameter([

			# 设置主体
			'main' => 'admin.discussion',	
			
		], true);
		
        # 必须为管理员以上权限
        $this->auth->check('admin');

	}
	
    /**
     * 绑定动作
     *
     * @access public
     * @return void
     */
    public function action()
    {
		$this->on(!$this->request->action || $this->request->is('action=index'))->index();
		$this->on($this->request->isPost() && (!$this->request->action || $this->request->is('action=index')))->update();
    }

    public function index()
    {
		/** 输出内容 */
		$this->layout->set($this->form(), 'body');
		
		$this->view();
    }
	
    /**
     * 输出表单结构
     *
     * @access public
     * @return Form
     */
    public function form()
    {
        /** 构建表格 */
        $form = Html::form();

        /** 评论日期格式 */
        $commentDateFormat = Html::text('commentDateFormat', $this->config->commentDateFormat)
		    ->label(__('评论日期格式'))
		    ->description(__('这是一个默认的格式,当你在模板中调用显示评论日期方法时, 如果没有指定日期格式, 将按照此格式输出.') . '<br />'
            . __('具体写法请参考 <a href="http://www.php.net/manual/zh/function.date.php">PHP 日期格式写法</a>.'));
        $form->addInput($commentDateFormat);

        /** 评论列表数目 */
        $commentsListSize = Html::text('commentsListSize', $this->config->commentsListSize)
		    ->label(__('评论列表数目'))
		    ->description(__('此数目用于指定显示在侧边栏中的评论列表数目.'))
			->addRule('int', __('请填入一个数字'));
        $form->addInput($commentsListSize);

        $commentsShowOptions = [
            'commentsShowUrl'         => __('评论者名称显示时自动加上其个人主页链接'),
            'commentsUrlNofollow'     => __('对评论者个人主页链接使用 <a href="http://en.wikipedia.org/wiki/Nofollow">nofollow 属性</a>'),
            'commentsPageBreak'     =>  __('启用分页, 并且每页显示 %s 篇评论, 在列出时将 %s 作为默认显示',
            ['</label><input class="d-inline-block form-control form-control-sm" type="text" value="' . $this->config->commentsPageSize
            . '" style="width:40px;" id="commentsShow-commentsPageSize" name="commentsPageSize" /><label for="commentsShow-commentsPageSize">',
            '</label><select class="w-auto d-inline-block form-control form-control-sm" id="commentsShow-commentsPageDisplay" name="commentsPageDisplay">
            <option value="first"' . ('first' == $this->config->commentsPageDisplay ? ' selected="true"' : '') . '>' . __('第一页') . '</option>
            <option value="last"' . ('last' == $this->config->commentsPageDisplay ? ' selected="true"' : '') . '>' . __('最后一页') . '</option></select>'
            . '<label for="commentsShow-commentsPageDisplay">']),
			
            'commentsThreaded'      =>  __('启用评论回复, 以 %s 层作为每个评论最多的回复层数',
            ['</label><input class="d-inline-block form-control form-control-sm" name="commentsMaxNestingLevels" type="text" style="width:40px;" value="' . $this->config->commentsMaxNestingLevels . '" id="commentsShow-commentsMaxNestingLevels" />
            <label for="commentsShow-commentsMaxNestingLevels">']) . '</label></span><span class="multiline">'
            . __('将 %s 的评论显示在前面', ['<select class="w-auto d-inline-block form-control form-control-sm" id="commentsShow-commentsOrder" name="commentsOrder">
            <option value="DESC"' . ('DESC' == $this->config->commentsOrder ? ' selected="true"' : '') . '>' . __('较新的') . '</option>
            <option value="ASC"' . ('ASC' == $this->config->commentsOrder ? ' selected="true"' : '') . '>' . __('较旧的') . '</option></select><label for="commentsShow-commentsOrder">'])
        ];

        $commentsShowOptionsValue = [];

        if ($this->config->commentsShowUrl) {
            $commentsShowOptionsValue[] = 'commentsShowUrl';
        }

        if ($this->config->commentsUrlNofollow) {
            $commentsShowOptionsValue[] = 'commentsUrlNofollow';
        }

        if ($this->config->commentsPageBreak) {
            $commentsShowOptionsValue[] = 'commentsPageBreak';
        }

        if ($this->config->commentsThreaded) {
            $commentsShowOptionsValue[] = 'commentsThreaded';
        }

        $commentsShow = Html::checkbox('commentsShow', $commentsShowOptions, $commentsShowOptionsValue)
		    ->label(__('评论显示'));
        $form->addInput($commentsShow);

        /** 评论提交 */
        $commentsPostOptions = [
            'commentsRequireModeration'     => __('所有评论必须经过审核'),
            'commentsWhitelist'             => __('评论者之前须有评论通过了审核'),
            'commentsCheckReferer'          =>  __('检查评论来源页 URL 是否与文章链接一致'),
            'commentsAutoClose'             =>  __('在文章发布 %s 天以后自动关闭评论',
            ['</label><input class="d-inline-block form-control form-control-sm" name="commentsPostTimeout" type="text" style="width:40px;" value="' . intval($this->config->commentsPostTimeout / (24 * 3600)) . '" id="commentsPost-commentsPostTimeout" />
            <label for="commentsPost-commentsPostTimeout">']),
            'commentsPostIntervalEnable'    =>  __('同一 IP 发布评论的时间间隔限制为 %s 分钟',
            ['</label><input class="d-inline-block form-control form-control-sm" name="commentsPostInterval" type="text" style="width:40px;" value="' . round($this->config->commentsPostInterval / (60), 1) . '" id="commentsPost-commentsPostInterval" />
            <label for="commentsPost-commentsPostInterval">'])
        ];
		
		$commentsPostOptionsValue = [];
		
        if ($this->config->commentsRequireModeration) {
            $commentsPostOptionsValue[] = 'commentsRequireModeration';
        }

        if ($this->config->commentsWhitelist) {
            $commentsPostOptionsValue[] = 'commentsWhitelist';
        }
		
        if ($this->config->commentsCheckReferer) {
            $commentsPostOptionsValue[] = 'commentsCheckReferer';
        }

        if ($this->config->commentsAutoClose) {
            $commentsPostOptionsValue[] = 'commentsAutoClose';
        }

        if ($this->config->commentsPostIntervalEnable) {
            $commentsPostOptionsValue[] = 'commentsPostIntervalEnable';
        }

        $commentsPost = Html::checkbox('commentsPost', $commentsPostOptions, $commentsPostOptionsValue)
		    ->label(__('评论提交'));
        $form->addInput($commentsPost);

        /** 允许使用的HTML标签和属性 */
        $commentsHtmlTagAllowed = Html::textarea('commentsHtmlTagAllowed', $this->config->commentsHtmlTagAllowed)
		    ->label(__('允许使用的HTML标签和属性'))
		    ->description(__('默认的用户评论不允许填写任何的HTML标签, 你可以在这里填写允许使用的HTML标签.') . '<br />'
            . __('比如: %s', ['<code>&lt;a href=&quot;&quot;&gt; &lt;img src=&quot;&quot;&gt; &lt;blockquote&gt;</code>']));
        $form->addInput($commentsHtmlTagAllowed);

        /** 提交按钮 */
        $submit = Html::submit(__('保存设置'));
        $form->set($submit);
		
        return $form;
    }

    /**
     * 执行更新动作
     *
     * @access public
     * @return void
     */
    public function update()
    {
		$form = $this->form();
		
		/** 验证格式 */
        if ($form->validate()) {
            $this->goBack();
        }

        $settings = $this->request->from(
		    'commentDateFormat', 
		    'commentsListSize',
			'commentsPageSize', 
		    'commentsPageDisplay',
			'commentsOrder', 
		    'commentsMaxNestingLevels',
			'commentsPostTimeout', 
		    'commentsPostInterval',
			'commentsHtmlTagAllowed'
		);
		
        $commentsShow = $this->request->getArray('commentsShow');
        $commentsPost = $this->request->getArray('commentsPost');

        $settings['commentsShowUrl'] = $this->isEnableByCheckbox($commentsShow, 'commentsShowUrl');
        $settings['commentsUrlNofollow'] = $this->isEnableByCheckbox($commentsShow, 'commentsUrlNofollow');
        $settings['commentsPageBreak'] = $this->isEnableByCheckbox($commentsShow, 'commentsPageBreak');
        $settings['commentsThreaded'] = $this->isEnableByCheckbox($commentsShow, 'commentsThreaded');
		
        $settings['commentsRequireModeration'] = $this->isEnableByCheckbox($commentsPost, 'commentsRequireModeration');
        $settings['commentsWhitelist'] = $this->isEnableByCheckbox($commentsPost, 'commentsWhitelist');
        $settings['commentsPageSize'] = intval($settings['commentsPageSize']);
        $settings['commentsMaxNestingLevels'] = min(7, max(2, intval($settings['commentsMaxNestingLevels'])));
        $settings['commentsPageDisplay'] = ('first' == $settings['commentsPageDisplay']) ? 'first' : 'last';
        $settings['commentsOrder'] = ('DESC' == $settings['commentsOrder']) ? 'DESC' : 'ASC';

        $settings['commentsCheckReferer'] = $this->isEnableByCheckbox($commentsPost, 'commentsCheckReferer');
        $settings['commentsAutoClose'] = $this->isEnableByCheckbox($commentsPost, 'commentsAutoClose');
        $settings['commentsPostIntervalEnable'] = $this->isEnableByCheckbox($commentsPost, 'commentsPostIntervalEnable');

        $settings['commentsPostTimeout'] = intval($settings['commentsPostTimeout']) * 24 * 3600;
        $settings['commentsPostInterval'] = round($settings['commentsPostInterval'], 1) * 60;
		
        foreach ($settings as $name => $value) 
		{
            $this->updateOptions($name, $value);
        }
		
        $this->notice(__("设置已经保存"));
		
		$this->goBack();
    }

    /**
     * 以checkbox选项判断是否某个值被启用
     *
     * @access protected
     * @param mixed $settings 选项集合
     * @param string $name 选项名称
     * @return integer
     */
    protected function isEnableByCheckbox($settings, $name)
    {
        return is_array($settings) && in_array($name, $settings) ? 1 : 0;
    }
}
